<template>
  <div class="back-to-top" v-if="isVisible" @click="scrollToTop">
    <i class="iconfont">&#xe60d;</i>
    <span>顶部</span>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';

const isVisible = ref(false);

const handleScroll = () => {
  isVisible.value = window.scrollY > 300;
};

const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

onMounted(() => {
  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style scoped lang="scss">
.back-to-top {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background-color: #fff;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 8px; /* 圆角 */
  box-sizing: border-box;
  // width: 40px; /* 增加宽度以适应文字 */
  // height: 40px; /* 自动高度 */
  display: flex;
  flex-direction: column; /* 文字在图标下面 */
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 更深的阴影 */
  cursor: pointer;
  transition: background-color 0.3s ease; /* 添加过渡效果 */

  i {
    font-size: 12px;
    color: #0d1216;
  }

  span {
    font-size: 12px;
    color: #0d1216;
    margin-top: 5px; /* 图标和文字之间的间距 */
  }

  &:hover {
    background-color: #f0f0f0;
  }
}
</style>
